package com.flow.server.modules.cmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 描述：处理流程Bpmn工具类
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/8/30 17:06 星期五
 */
public class BpmnBuilderUtil {

    private static Logger logger = LoggerFactory.getLogger(BpmnBuilderUtil.class);

    /**
     * 从 Request 对象构造 BpmnCmd 对象
     *
     * @return BpmnModelCmd
     */
    public static BpmnModelCmd buildBpmnCmd(HttpServletRequest request) {
        BpmnModelCmd.BpmnModelCmdBuilder builder = BpmnModelCmd.builder();

        String key = request.getParameter("key");
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        String description = request.getParameter("description");
        String status = request.getParameter("status");
        String jsonXml = request.getParameter("json_xml");
        String svgXml = request.getParameter("svg_xml");
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        builder.name(name).jsonXml(jsonXml).svgXml(svgXml).version(1)
                .key(StringUtils.isNotEmpty(key) ? key : null).status(status)
                .category(StringUtils.isNotEmpty(category) ? category : null)
                .description(StringUtils.isNotEmpty(description) ? description : null)
                .pageNum(StringUtils.isNoneEmpty(pageNum) ? Integer.parseInt(pageNum) : 1)
                .pageSize(StringUtils.isNoneEmpty(pageSize) ? Integer.parseInt(pageSize) : 10);

        logger.debug("从 Request 对象构造 BpmnCmd 对象:{}", JSON.toJSONString(builder.build()));
        return builder.build();
    }

    /**
     * 从 Request 对象构造 List<BpmnDefinitionCmd> 对象
     *
     * @return BpmnDefinitionCmd
     */
    public static List<BpmnDefinitionCmd> buildBpmnDefinitionCmd(HttpServletRequest request) throws IOException {
        List<BpmnDefinitionCmd> list = new ArrayList<>();
        BpmnDefinitionCmd.BpmnDefinitionCmdBuilder builder = BpmnDefinitionCmd.builder();

        String nodeSettings = request.getParameter("nodeSettings");

        if (StringUtils.isNotEmpty(nodeSettings) && !"[]".equals(nodeSettings)) {
            List<Map> settings = JSON.parseArray(nodeSettings, Map.class);
            if (null != settings && settings.size() != 0) {
                settings.forEach(json -> {
                    String modelId = String.valueOf(json.get("modelId"));
                    String key = String.valueOf(json.get("key"));
                    String nodeId = String.valueOf(json.get("nodeId"));
                    String nodeType = String.valueOf(json.get("nodeType"));
                    String nodeUser = String.valueOf(json.get("nodeUser"));
                    String nodeCopyUser = String.valueOf(json.get("nodeCopyUser"));
                    String nodeForm = String.valueOf(json.get("nodeForm"));
                    String nodeBtn = String.valueOf(json.get("nodeBtn"));
                    String nodeGate = String.valueOf(json.get("nodeGate"));
                    String nodeJumpType = String.valueOf(json.get("nodeJumpType"));
                    String nodeDueDate = String.valueOf(json.get("nodeDueDate"));

                    builder.modelId(modelId).key(key).nodeId(nodeId).nodeType(nodeType).nodeJumpType(nodeJumpType);

                    if (StringUtils.isNotEmpty(nodeUser) && !"[]".equals(nodeUser)) {
                        List<Map> mapList = JSON.parseArray(nodeUser, Map.class);
                        builder.nodeUser(mapList);
                    } else {
                        builder.nodeUser(Lists.newArrayList());
                    }

                    if (StringUtils.isNotEmpty(nodeCopyUser) && !"[]".equals(nodeCopyUser)) {
                        List<Map> mapList = JSON.parseArray(nodeCopyUser, Map.class);
                        builder.nodeCopyUser(mapList);
                    } else {
                        builder.nodeCopyUser(Lists.newArrayList());
                    }

                    if (StringUtils.isNotEmpty(nodeForm) && !"[]".equals(nodeForm)) {
                        List<Map> mapList = JSON.parseArray(nodeForm, Map.class);
                        mapList.sort(Comparator.comparing(map -> map.get("formType").toString()));
                        builder.nodeForm(mapList);
                    } else {
                        builder.nodeForm(Lists.newArrayList());
                    }

                    if (StringUtils.isNotEmpty(nodeGate) && !"[]".equals(nodeGate)) {
                        List<Map> mapList = JSON.parseArray(nodeGate, Map.class);
                        builder.nodeGate(mapList);
                    } else {
                        builder.nodeGate(Lists.newArrayList());
                    }

                    if (StringUtils.isNotEmpty(nodeBtn)) {
                        builder.nodeBtn(nodeBtn);
                    } else {
                        builder.nodeBtn("");
                    }

                    if (StringUtils.isNotEmpty(nodeDueDate) && !"{}".equals(nodeDueDate)) {
                        JSONObject nodeDueDateObj = JSONObject.parseObject(nodeDueDate);
                        builder.nodeDueDateType(nodeDueDateObj.get("timeLimitType").toString());
                        builder.nodeDueDate(nodeDueDateObj.get("dateNum").toString());
                    } else {
                        builder.nodeDueDate("");
                        builder.nodeDueDateType("0");
                    }

                    list.add(builder.build());
                });
            }
        }
        return list;
    }

    /**
     * 从 Request 对象构造 ProcessInstanceCmd 对象
     *
     * @return ProcessInstanceCmd
     */
    public static ProcessInstanceCmd buildProcessInstanceCmd(HttpServletRequest request) {
        ProcessInstanceCmd.ProcessInstanceCmdBuilder builder = ProcessInstanceCmd.builder();
//        UserDto user = UserUtil.getUserFromRedis();

//        ActDefinitionDao actDefinitionDao = (ActDefinitionDao) ContextFactoryUtil.getBean("actDefinitionDao");
        String instanceId = request.getParameter("instanceId");
        String instanceName = request.getParameter("instanceName");
        String suspensionState = request.getParameter("suspensionState");
        String category = request.getParameter("category");
        String processDefKey = request.getParameter("processDefKey");
        String processDefId = request.getParameter("processDefId");
        String taskDefKey = request.getParameter("taskDefKey");
        String businessId = request.getParameter("businessId");
        String extInstanceId = request.getParameter("extInstanceId");
        String extInstanceName = request.getParameter("extInstanceName");
        String startUserId = request.getParameter("currUserId");
        String startUserName = request.getParameter("currUserName");
        String isDraft = request.getParameter("isDraft");
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        Map<String, Object> variables = new HashMap<>();
//        if (actDefinitionDao != null) {
//            ActNodeConfigEntity actNodeConfigEntity = new ActNodeConfigEntity();
//            actNodeConfigEntity.setConfigType("gateWay");
//            actNodeConfigEntity.setKey(key);
//            //获取流程设置时的变量信息
//            List<ActNodeConfigEntity> nodeConfigEntities = actDefinitionDao.getProcessDefinitionSettings(actNodeConfigEntity);
//            nodeConfigEntities.forEach(nodeConfigEntity -> {
//                String configValue = nodeConfigEntity.getConfigValue();
//                List<Map<String, String>> list = RegexUtil.renderELAnyString(configValue);
//                list.forEach(var -> {
//                    String varKey = var.keySet().iterator().next();
//                    variables.put(varKey, var.get(varKey));
//                });
//            });
//        }

        builder.processDefId(processDefId).processDefKey(processDefKey).instanceId(instanceId).instanceName(instanceName)
                .startUserId(startUserId).startUserName(startUserName).businessId(businessId).variables(variables)
                .isDraft(isDraft).extInstanceName(extInstanceName).taskDefKey(taskDefKey).category(category)
                .suspensionState(StringUtils.isNotEmpty(suspensionState) ? suspensionState : "")
                .pageNum(StringUtils.isNoneEmpty(pageNum) ? Integer.parseInt(pageNum) : 1)
                .pageSize(StringUtils.isNoneEmpty(pageSize) ? Integer.parseInt(pageSize) : 10);
        ;
        return builder.build();
    }

    /**
     * 从 Request 对象构造 TaskHandleCmd 对象
     *
     * @return TaskHandleCmd
     */
    public static TaskHandleCmd buildTaskHandleCmd(HttpServletRequest request) {
        TaskHandleCmd.TaskHandleCmdBuilder builder = TaskHandleCmd.builder();
//        UserDto user = UserUtil.getUserFromRedis();
//        if (user == null) {
//            throw new CustomerException("获取登录用户失败");
//        }
//
//        String key = request.getParameter("key");
//        String businessId = request.getParameter("businessId");
//        String currNodeId = request.getParameter("currNodeId");
//        String comment = request.getParameter("comment");
//        String attachment = request.getParameter("attachment");
//        String operateType = request.getParameter("operateType");
//        String operateUserName = request.getParameter("operateUserName");
//        String operateUserId = request.getParameter("operateUserId");
//        String operateDate = request.getParameter("operateDate");
//        String variables = request.getParameter("variables");
//        String nextCandidateInfos = request.getParameter("nextCandidateInfos");
//        String nextCopyInfos = request.getParameter("nextCopyInfos");
//
//        Map<String, Object> mapVariables = Maps.newHashMap();
//        if (StringUtils.isNotEmpty(variables) && !"undefined".equalsIgnoreCase(variables)) {
//            JSONObject jsonObject = JSONObject.parseObject(variables);
//            Set<String> keySet = jsonObject.keySet();
//            keySet.forEach(varKey -> mapVariables.put(varKey, jsonObject.get(varKey)));
//        }
//
//        Task task = WorkflowUtils.getTaskById(currNodeId);
//        if (task == null) {
//            throw new CustomerException("未查询到此任务");
//        }
//        //候选人
//        if (StringUtils.isNotEmpty(nextCandidateInfos) && !"[]".equals(nextCandidateInfos)) {
//            List<Map> mapList = JSON.parseArray(nextCandidateInfos, Map.class);
//            builder.nextCandidateInfos(mapList);
//        }
//        //抄送人
//        if (StringUtils.isNotEmpty(nextCopyInfos) && !"[]".equals(nextCopyInfos)) {
//            List<Map> mapList = JSON.parseArray(nextCopyInfos, Map.class);
//            builder.nextCopyInfos(mapList);
//        }
//        builder.key(key).instanceId(task.getProcessInstanceId()).processDefId(task.getProcessDefinitionId())
//                .businessId(businessId).currNodeId(currNodeId).currNodeKey(task.getTaskDefinitionKey())
//                .currNodeName(task.getName()).comment(comment).attachment(attachment).variables(mapVariables)
//                .operateDate(DateUtil.stringConvertToDate(operateDate, "yyyy-MM-dd HH:mm:ss"))
//                .operateType(operateType).operateUserName(user.getName()).operateUserId(user.getId());
//
//        logger.debug("从 Request 对象构造 TaskHandleCmd 对象:{}", JSON.toJSONString(builder.build()));
        return builder.build();
    }
}
